<template>
  <el-dialog title="新增员工" top="8vh" :visible="showDialog" @open="handleOpen" @close="handleClose">
    <!-- 表单 -->
    <el-form ref="addForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="formData.username" style="width:50%" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="formData.mobile" style="width:50%" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker v-model="formData.timeOfEntry" style="width:50%" placeholder="请选择入职时间" />
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="formData.formOfEmployment" style="width:50%" placeholder="请选择">
          <el-option v-for="list in hireType" :key="list.id" :value="list.id" :label="list.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="formData.workNumber" style="width:50%" placeholder="请输入工号" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <el-input v-model="formData.departmentName" style="width:50%" placeholder="请选择部门" @focus="getDepartList" />
        <el-tree
          v-if="showTree"
          v-loading="loading"
          :data="depart"
          class="tree-box"
          :props="{label:'name'} "
          @node-click="selectNode"
        />
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <el-date-picker v-model="formData.correctionTime" style="width:50%" placeholder="请选择转正时间" />
      </el-form-item>
    </el-form>
    <!-- footer插槽 -->
    <template v-slot:footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Types from '@/api/constant/employees'
import { reqAddEmployee } from '@/api/employees'
// 获取部门列表数据,以供新增员工弹窗选择
import { reqGetDepartments } from '@/api/departments'
export default {
  name: 'AddEmployee',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 是否显示tree
      showTree: false,
      //   控制加载状态
      //   loading: false,
      // 定义一个空数组来接收部门列表数据
      depart: [],
      hireType: Types.hireType,
      formData: {
        username: '', // 用户名
        mobile: '', // 手机号
        formOfEmployment: '', // 聘用形式
        workNumber: '', // 工号
        departmentName: '', // 部门
        timeOfEntry: '', // 入职时间
        correctionTime: '' // 转正时间
      },
      rules: {
        username: [
          { required: true, message: '用户姓名不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 4, message: '用户姓名为1-4位', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: ['blur', 'change'] },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }
        ],
        formOfEmployment: [
          { required: true, message: '聘用形式不能为空', trigger: ['blur', 'change'] }
        ],
        workNumber: [
          { required: true, message: '工号不能为空', trigger: ['blur', 'change'] }
        ],
        departmentName: [
          { required: true, message: '部门不能为空', trigger: ['blur', 'change'] }
        ],
        timeOfEntry: [
          { required: true, message: '请选择入职时间', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getDepartList()
  },
  methods: {
    //   选中其中一个节点
    selectNode(dept) {
      // 控制叶子节点
      if (dept.children && dept.children.length > 0) {
        // 获取部门的名称
        this.formData.departmentName = dept.name
        // 隐藏树形结构
        this.showTree = false
      }
    },
    //   点击提交
    handleSubmit() {
      // 提交之前先做个全局兜底校验
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        try {
          // 开始提交数据
          const ret = await reqAddEmployee(this.formData)
          // console.log(ret)
          if (ret.code === 10000) {
            this.$message.success('新增员工成功')
            this.$emit('update:show-dialog', false)
            this.$emit('on-success')
          } else {
            this.$message.error('新增员工失败')
          }
        } catch {
          this.$message.error('添加员工失败')
        }
      })
    },
    //   获取部门列表之前先将数据结构转换为树形结构
    translateListToTreeData(list, id) {
      const result = []
      // list表示原始的列表数据
      // id表示当前节点的id，根据它可以找到他的子节点

      // 遍历list每一个节点，并且找到每一个节点的所有子节点
      // 找到的所有子节点放到数组children中，把children属性赋值给当前节点对象即可
      list.forEach(item => {
        if (item.pid === id) {
          // 查找item当前节点的子节点
          const children = this.translateListToTreeData(list, item.id)
          if (children && children.length > 0) {
            item.children = children
          }
          result.push(item)
        }
      })
      // 返回值表示整个转化后的树形结构
      return result
    },
    //   获取部门列表数据
    async getDepartList() {
      try {
        //   树形列表展示
        this.showTree = true
        // 加载状态开启
        this.loading = true
        const ret = await reqGetDepartments()
        //   console.log(ret)
        this.depart = this.translateListToTreeData(ret.data.depts, '')
        this.loading = false
      } catch {
        this.$message.error('获取部门列表数据失败')
      } finally {
        this.loading = false
      }
    },
    //   点击新增员工弹窗打开
    handleOpen() {
      this.showDialog = true
      this.showTree = false
    },
    //   点击取消关闭弹窗
    handleClose() {
      this.$emit('update:show-dialog', false)
      //   清空表单
      this.$refs.addForm.resetFields()
      this.addForm = this.$options.data().addForm
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-box {
  position: absolute;
  width: 50%;
  min-height: 50px;
  left: 0;
  top: 45px;
  z-index: 100;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding-right: 5px;
  overflow: hidden;
  background-color: #fff;
}
</style>
